package com.example.myapplication.service

import android.content.Context
import com.example.myapplication.api.BackendApiClient
import com.example.myapplication.database.PositionRepository
import com.example.myapplication.model.TradingSignal
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.*

/**
 * 交易信号自动记录服务
 * 用于自动记录所有推荐股票的买入/卖出信号到数据库，供回测使用
 */
class SignalRecordService(private val context: Context) {
    
    private val apiClient = BackendApiClient(context)
    private val positionRepository = PositionRepository(context)
    
    companion object {
        private const val DEFAULT_QUANTITY = 100 // 默认买卖数量（股）
        private const val DUPLICATE_THRESHOLD_MS = 24 * 60 * 60 * 1000L // 24小时内视为重复
    }
    
    /**
     * 自动记录所有推荐股票的交易信号
     * 这个方法会：
     * 1. 获取所有推荐买入的股票列表
     * 2. 为每只股票获取交易信号
     * 3. 自动保存买入/卖出信号到数据库
     */
    suspend fun recordAllRecommendedStocks(): RecordResult = withContext(Dispatchers.IO) {
        val result = RecordResult()
        
        try {
            android.util.Log.d("📝信号记录", "开始记录推荐股票的交易信号...")
            
            // 1. 获取推荐买入股票列表
            val recommendedStocks = apiClient.getRecommendedBuyStocks()
            result.totalStocks = recommendedStocks.size
            
            android.util.Log.d("📝信号记录", "获取到 ${recommendedStocks.size} 只推荐股票")
            
            // 2. 为每只股票处理交易信号
            for (stock in recommendedStocks) {
                try {
                    processStockSignal(stock.symbol, stock.name, result)
                } catch (e: Exception) {
                    android.util.Log.e("📝信号记录", "处理股票 ${stock.symbol} 失败: ${e.message}", e)
                    result.errorCount++
                }
            }
            
            // 3. 输出统计信息
            android.util.Log.d("📝信号记录", """
                ====== 信号记录完成 ======
                总股票数: ${result.totalStocks}
                新增买入: ${result.buySignalsRecorded}
                新增卖出: ${result.sellSignalsRecorded}
                重复跳过: ${result.duplicateSkipped}
                错误数量: ${result.errorCount}
                ==========================
            """.trimIndent())
            
        } catch (e: Exception) {
            android.util.Log.e("📝信号记录", "记录推荐股票信号失败: ${e.message}", e)
            result.error = e.message
        }
        
        return@withContext result
    }
    
    /**
     * 处理单只股票的交易信号
     */
    private suspend fun processStockSignal(symbol: String, name: String, result: RecordResult) {
        try {
            // 获取交易信号
            val signal = apiClient.getTradingSignal(symbol) ?: return
            
            val timestamp = System.currentTimeMillis()
            val dateStr = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).format(Date(timestamp))
            
            when {
                // 买入信号
                signal.isBuySignal() -> {
                    // 检查是否重复
                    if (isDuplicateBuySignal(symbol, timestamp)) {
                        android.util.Log.d("📝信号记录", "[$name] 买入信号已存在，跳过")
                        result.duplicateSkipped++
                        return
                    }
                    
                    val buyPrice = signal.actionPrice ?: signal.price
                    
                    // 记录买入
                    positionRepository.recordBuy(
                        symbol = symbol,
                        stockName = name,
                        price = buyPrice,
                        quantity = DEFAULT_QUANTITY,
                        timestamp = timestamp,
                        reason = signal.reason,
                        signalStrength = signal.strength
                    )
                    
                    result.buySignalsRecorded++
                    android.util.Log.d("📝信号记录", "[$name] ✅ 记录买入信号: ¥$buyPrice @ $dateStr")
                }
                
                // 卖出信号
                signal.isSellSignal() -> {
                    // 检查是否有持仓
                    val openPositions = positionRepository.getOpenBuyPositions(symbol)
                    
                    if (openPositions.isEmpty()) {
                        android.util.Log.d("📝信号记录", "[$name] 无持仓，跳过卖出信号")
                        return
                    }
                    
                    val sellPrice = signal.actionPrice ?: signal.price
                    
                    // 记录卖出
                    positionRepository.recordSell(
                        symbol = symbol,
                        stockName = name,
                        price = sellPrice,
                        quantity = DEFAULT_QUANTITY,
                        timestamp = timestamp,
                        reason = signal.reason,
                        signalStrength = signal.strength
                    )
                    
                    // 计算收益
                    val buyPosition = openPositions.first()
                    val profit = (sellPrice - buyPosition.price) * DEFAULT_QUANTITY
                    val profitRate = (sellPrice - buyPosition.price) / buyPosition.price * 100
                    
                    result.sellSignalsRecorded++
                    android.util.Log.d("📝信号记录", 
                        "[$name] ✅ 记录卖出信号: ¥$sellPrice @ $dateStr, 收益: ${profitRate.format(2)}%")
                }
                
                else -> {
                    // 持有信号，不记录
                    android.util.Log.d("📝信号记录", "[$name] 持有信号，跳过")
                }
            }
            
        } catch (e: Exception) {
            android.util.Log.e("📝信号记录", "处理 $symbol 信号失败: ${e.message}", e)
            throw e
        }
    }
    
    /**
     * 检查是否为重复的买入信号
     * 判断逻辑：24小时内同一股票的买入记录视为重复
     */
    private suspend fun isDuplicateBuySignal(symbol: String, timestamp: Long): Boolean {
        val openPositions = positionRepository.getOpenBuyPositions(symbol)
        
        return openPositions.any { position ->
            val timeDiff = Math.abs(timestamp - position.timestamp)
            timeDiff < DUPLICATE_THRESHOLD_MS
        }
    }
    
    /**
     * 记录指定股票的信号（单只股票）
     */
    suspend fun recordStockSignal(symbol: String, name: String): Boolean = withContext(Dispatchers.IO) {
        try {
            val result = RecordResult()
            processStockSignal(symbol, name, result)
            return@withContext result.buySignalsRecorded > 0 || result.sellSignalsRecorded > 0
        } catch (e: Exception) {
            android.util.Log.e("📝信号记录", "记录 $symbol 信号失败: ${e.message}", e)
            return@withContext false
        }
    }
    
    // Double扩展函数：格式化小数位数
    private fun Double.format(digits: Int) = "%.${digits}f".format(this)
}

/**
 * 记录结果数据类
 */
data class RecordResult(
    var totalStocks: Int = 0,
    var buySignalsRecorded: Int = 0,
    var sellSignalsRecorded: Int = 0,
    var duplicateSkipped: Int = 0,
    var errorCount: Int = 0,
    var error: String? = null
) {
    val isSuccess: Boolean
        get() = error == null
    
    val totalRecorded: Int
        get() = buySignalsRecorded + sellSignalsRecorded
}

